package com.cainaer.auth.handler;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.cainaer.common.core.constant.Constants;
import com.cainaer.common.core.utils.StringUtils;
import com.cainaer.common.security.domain.LoginUser;
import com.cainaer.system.api.RemoteLogService;

/**
 * 认证成功处理
 *
 * @author cainaer
 */
@Component
public class AuthenticationSuccessEventHandler implements ApplicationListener<AuthenticationSuccessEvent> {
    @Autowired
    private RemoteLogService remoteLogService;

    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {

        Authentication authentication = (Authentication) event.getSource();

      //  System.out.println("getPrincipal={}"+authentication.getPrincipal());

        if (StringUtils.isNull(authentication.getPrincipal())){
            String jsonString = JSONObject.toJSONString(authentication.getPrincipal());
          //  System.out.println("jsonString One={}"+jsonString);
        }

        String jsonString = JSONObject.toJSONString(authentication.getPrincipal());
     //   System.out.println("jsonString Two={}"+jsonString.concat("username").getBytes());


        if (StringUtils.isNotEmpty(authentication.getAuthorities())
                && authentication.getPrincipal() instanceof LoginUser) {
            LoginUser user = (LoginUser) authentication.getPrincipal();
            String username = user.getUsername();

            // 记录用户登录日志
            remoteLogService.saveLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        }
    }
}
